package davidlauzon.activerecord.manager;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import davidlauzon.activerecord.nodes.InsertStatement;
import davidlauzon.activerecord.nodes.SqlStatement;
import davidlauzon.activerecord.nodes.Table;
import davidlauzon.activerecord.nodes.field.Field;


public class InsertManager extends StatementManager
{
    private InsertStatement _statement;

    private Table    _table;
    private Field[]  _columns;
    private Object[] _values;

    
    public InsertManager() {
        super();
    }
    
    public void reset() {
        super.reset();
       _table   = null;
       _columns = null;
       _values  = null;
    }
    
    public InsertManager into(Table into) {
        _table = into;
        setConnection(    _table.getConnection() );
        setSqlSerializer( _table.getConnection().getSerializer() );
        return this;
    }
    
    public InsertManager columns(Field[] columns) {
        _columns = columns;
        return this;
    }
    
    public InsertManager columns(List<Field> columns) {
        _columns = (Field[]) columns.toArray( new Field[columns.size()] );
        return this;
    }
    
    public InsertManager values(Object[] values) {
        _values = values;
        return this;
    }
    
    public InsertManager values(List<Object> values) {
        _values = (Field[]) values.toArray( new Object[values.size()] );
        return this;
    }
    
    public InsertManager values(Map<Field, Object> values) {
        int pos  = 0;
        int size = values.size();
        _columns = new Field[size];
        _values  = new Object[size];
        
        for (Field field : values.keySet()) {
            _columns[pos] = field;
            _values[pos]  = values.get(field);
            pos++;
        }
        return this;
    }
    
    @Override
    protected SqlStatement buildStatement() {
        if (_columns == null)
            _columns = _table.getFieldsWithoutPK();
        
        _statement = new InsertStatement();
        _statement.setInto(_table);
        _statement.setColumns(_columns);
        _statement.setValues(_values);
        
        return _statement;
    }
    
    public long insert() throws SQLException {
        String sql = this.toSql();
        return getConnection().executeInsert( sql );
    }
    
    public void insertLater() throws SQLException {
        String sql = this.toSql();
        getConnection().updateLater( sql );
    }
}
